package controller

import (
	"net/http"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"github.com/gin-gonic/gin"
)

// TimeZoneController 时区控制器
type TimeZoneController struct{}

// NewTimeZoneController 创建时区控制器实例
func NewTimeZoneController() *TimeZoneController {
	return &TimeZoneController{}
}

// GetCurrentTime 获取当前时间（支持多时区）
func (c *TimeZoneController) GetCurrentTime(ctx *gin.Context) {
	// 获取用户时区
	userTimezone := middleware.GetUserTimezone(ctx)

	// 获取当前时间
	now := common.Now()
	nowUTC := common.NowUTC()
	nowDisplay := common.NowInDisplay()

	// 获取用户时区的当前时间
	userTime := now
	if userTimezone != common.GetTimeZone().DefaultTimeZone {
		userTime, _ = common.ConvertTimeZone(now, common.GetTimeZone().DefaultTimeZone, userTimezone)
	}

	// 获取时区偏移量
	offset, _ := common.GetTimeZoneOffset(userTimezone)

	response := gin.H{
		"code": "0000",
		"msg": map[string]string{
			"CN": "获取时间成功",
			"EN": "Get time successfully",
			"VN": "Lấy thời gian thành công",
		},
		"data": gin.H{
			"user_timezone":   userTimezone,
			"timezone_abbr":   common.GetTimeZoneAbbr(userTimezone),
			"timezone_offset": offset,
			"times": gin.H{
				"user_time": gin.H{
					"time":      userTime.Format("2006-01-02 15:04:05"),
					"timestamp": userTime.Unix(),
					"timezone":  userTimezone,
				},
				"utc_time": gin.H{
					"time":      nowUTC.Format("2006-01-02 15:04:05"),
					"timestamp": nowUTC.Unix(),
					"timezone":  "UTC",
				},
				"display_time": gin.H{
					"time":      nowDisplay.Format("2006-01-02 15:04:05"),
					"timestamp": nowDisplay.Unix(),
					"timezone":  common.GetTimeZone().DisplayTimeZone,
				},
			},
		},
	}

	common.Success(ctx, response)
}

// GetTimeZones 获取支持的时区列表
func (c *TimeZoneController) GetTimeZones(ctx *gin.Context) {
	timezones := []gin.H{}

	for abbr, fullName := range common.TimeZoneMap {
		offset, _ := common.GetTimeZoneOffset(fullName)
		timezones = append(timezones, gin.H{
			"abbr":      abbr,
			"full_name": fullName,
			"offset":    offset,
		})
	}

	response := gin.H{
		"code": "0000",
		"msg": map[string]string{
			"CN": "获取时区列表成功",
			"EN": "Get timezone list successfully",
			"VN": "Lấy danh sách múi giờ thành công",
		},
		"data": gin.H{
			"timezones": timezones,
			"total":     len(timezones),
		},
	}

	common.Success(ctx, response)
}

// ConvertTime 转换时间到指定时区
func (c *TimeZoneController) ConvertTime(ctx *gin.Context) {
	var req struct {
		Time     string `json:"time" binding:"required"`
		FromZone string `json:"from_zone" binding:"required"`
		ToZone   string `json:"to_zone" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 解析时间
	fromTime, err := common.ParseTimeInZone(req.Time, req.FromZone)
	if err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_time_format", err)
		return
	}

	// 转换时区
	toTime, err := common.ConvertTimeZone(fromTime, req.FromZone, req.ToZone)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "timezone_conversion_failed", err)
		return
	}

	response := gin.H{
		"code": "0000",
		"msg": map[string]string{
			"CN": "时间转换成功",
			"EN": "Time conversion successful",
			"VN": "Chuyển đổi thời gian thành công",
		},
		"data": gin.H{
			"from_time": gin.H{
				"time":          fromTime.Format("2006-01-02 15:04:05"),
				"timestamp":     fromTime.Unix(),
				"timezone":      req.FromZone,
				"timezone_abbr": common.GetTimeZoneAbbr(req.FromZone),
			},
			"to_time": gin.H{
				"time":          toTime.Format("2006-01-02 15:04:05"),
				"timestamp":     toTime.Unix(),
				"timezone":      req.ToZone,
				"timezone_abbr": common.GetTimeZoneAbbr(req.ToZone),
			},
		},
	}

	common.Success(ctx, response)
}

// GetBusinessHours 获取营业时间信息
func (c *TimeZoneController) GetBusinessHours(ctx *gin.Context) {
	var req struct {
		Timezone string `json:"timezone" binding:"required"`
		Date     string `json:"date"` // 可选，默认为今天
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 解析日期
	var targetDate time.Time
	if req.Date != "" {
		parsedDate, err := common.ParseTime(req.Date)
		if err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_date_format", err)
			return
		}
		targetDate = parsedDate
	} else {
		targetDate = common.Now()
	}

	// 获取营业时间信息
	businessStart := common.GetBusinessDayStart(targetDate, req.Timezone)
	businessEnd := common.GetBusinessDayEnd(targetDate, req.Timezone)
	isBusinessHours := common.IsBusinessHours(targetDate, req.Timezone)
	nextBusinessDay := common.GetNextBusinessDay(targetDate, req.Timezone)

	response := gin.H{
		"code": "0000",
		"msg": map[string]string{
			"CN": "获取营业时间成功",
			"EN": "Get business hours successfully",
			"VN": "Lấy giờ làm việc thành công",
		},
		"data": gin.H{
			"timezone": req.Timezone,
			"date":     targetDate.Format("2006-01-02"),
			"business_hours": gin.H{
				"start":             businessStart.Format("2006-01-02 15:04:05"),
				"end":               businessEnd.Format("2006-01-02 15:04:05"),
				"is_business_hours": isBusinessHours,
				"next_business_day": nextBusinessDay.Format("2006-01-02 15:04:05"),
			},
		},
	}

	common.Success(ctx, response)
}

// SetUserTimezone 设置用户时区
func (c *TimeZoneController) SetUserTimezone(ctx *gin.Context) {
	var req struct {
		Timezone string `json:"timezone" binding:"required"`
	}

	if err := ctx.ShouldBindJSON(&req); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证时区
	if err := common.ValidateTimeZone(req.Timezone); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_timezone", err)
		return
	}

	// 设置用户时区到上下文
	middleware.SetUserTimezone(ctx, req.Timezone)

	response := gin.H{
		"code": "0000",
		"msg": map[string]string{
			"CN": "设置时区成功",
			"EN": "Set timezone successfully",
			"VN": "Thiết lập múi giờ thành công",
		},
		"data": gin.H{
			"timezone":      req.Timezone,
			"timezone_abbr": common.GetTimeZoneAbbr(req.Timezone),
		},
	}

	common.Success(ctx, response)
}
